package com.yc.web.filter;



import com.yc.web.model.JsonModel;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import static com.yc.utils.YcConstants.USER;
;

//@WebFilter(value = "*.action")      //*.action拦截所有的请求
@WebFilter(filterName = "RightFilter",value = {"/custOp.action","/order.action","/alipay.action","/historical.action"})   //指拦截指定的两个请求地址
public class RightFilter extends CommonFilter{

//    public RightFilter(){
//        System.out.println("我是权限过滤器的构造方法，看我被调用几次：");
//    }
//
//    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
//        System.out.println("rightFilter的  init方法");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //doFilter类似于Servlet中的service方法
        //配置的请求都会经过这个方法
//        System.out.println("hello  world,I'm rightfilter");
        //即判断：httpSession中是否有resuser这个键   如果没有  则说明没有登录
        //如没有登录，则回送JsonModel的对象  code=0,msg的信息
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String op = request.getParameter("op");

        //再取sesion
        HttpSession session = request.getSession();
        if (session.getAttribute(USER)!=null){
            filterChain.doFilter(servletRequest,servletResponse);       //********极其重要   这样请求才可以继承向后
        }else{
            //要过滤的地址 ， 但是没登录
            JsonModel jm = new JsonModel();
            jm.setCode(-1);
            jm.setError("用户尚未登陆");
            super.writeJson(jm,response);
        }
    }

    @Override
    public void destroy() {

    }
}
